package com.cyou.nad.tag.table.pagebar;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

import com.cyou.nad.dao.Pagination;

public class SimplePageBar extends AbstractPageBar{

	private static  SimplePageBar bar = new SimplePageBar();
	public static SimplePageBar getInstance(){
		return bar;
	}
	@Override
	public String getHTML(HttpServletRequest req, Pagination page, String formAction) {
		Object obj = new Object();
		String formId = obj.hashCode()+"";
		String urlPageNo = req.getParameter(REQUEST_PARAMETER_PAGE);
		int currentPage = StringUtils.isBlank(urlPageNo) ? 1 : new Integer(urlPageNo).intValue();
		int totalPages = page.getTotalPageCount();
		int totalRows = page.getTotalCount();

		StringBuffer form = builderSearchForm(req, formId, formAction, totalRows, page.getPageSize());
		String navigation = getNav(formId, currentPage, totalPages, totalRows,page.getPageSize());
		return form.append(navigation).toString();
	}

	private String getNav(String formId, int currentPage, int totalPages, int totalRows, int pageSize) {
		String pagingHtml = "";
		int range = 2;
		int start = 1;
		int end = 1;
		
		if(totalPages <= range*2+1){
			start = 1;
			end = totalPages;
		}else if(currentPage - range < 1){
			start = 1;
			end = range*2+1;
		}else if(currentPage + range > totalPages){
			start = totalPages - range*2;
			end = totalPages;
		}else{
			start = currentPage - range;
			end = currentPage + range;
		}
		for(int i = start ; i <= end ; i++){
			if(i != currentPage){
				pagingHtml += "<li><a href='javascript:void(0);' onclick=\"gotoPage"+formId+"('" + formId + "'," + i + ","+pageSize+");\"><span>"+i+"</span></a></li>";

			}else{
				pagingHtml += "<li><a href='javascript:void(0);' class='current'><span>"+i+"</span></a></li>";
			}
		}
		if(currentPage != 1){
			pagingHtml = "<li><a href='javascript:void(0);' onclick=\"gotoPage"+formId+"('" + formId + "'," + (currentPage-1) + ","+pageSize+");\"><span>上一页</span></a></li>" + pagingHtml;
		}
		if(totalPages != 0){
			if(currentPage != totalPages){
				pagingHtml += "<li><a href='javascript:void(0);' onclick=\"gotoPage"+formId+"('" + formId + "'," + (currentPage+1) + ","+pageSize+");\"><span>下一页</span></a></li>";
			}
			String js ="<script type = 'text/javaScript'>\r\n";
			js+="function gotoPage"+formId+"(formId,pageNo,pageSize){" +
				"if(pageSize){ " +
				"	var form = document.getElementById('"+formId+"');" +
				"	form."+REQUEST_PARAMETER_PAGE_SIZE+".value = pageSize;" +
				"}" +
				"var pageId = '"+ REQUEST_PARAMETER_PAGE+ formId+ "';" +
				"var pageInput = document.getElementById(pageId);	" +
				"pageInput.value=pageNo;document.getElementById(formId).submit();}";
			js+="</script>";
			return pagingHtml+js;
		}
		else{
			return "没有任何题目!";
		}
	}

}
